import * as fs from "fs";

/**
 * 检测目录是否存在
 * @param {String} dir
 * @return {Promise<String>}
 */
export const isDirExist = async (dir: string): Promise<boolean> => {
    return Promise.resolve(fs.existsSync(dir))
}

/**
 * 获取文件扩展名
 * @param {String} originalName
 * @return {String}
 */
export const getExtName = (originalName: string): string => {
    return originalName.slice(originalName.lastIndexOf('.') + 1)
}

/**
 * 检测目录并创建
 * @param {String} filePath
 */
export const checkDirAndCreate = filePath => {
    const pathArr = filePath.split('/');
    let checkPath = '.';
    let item: string;
    for (item of pathArr) {
        checkPath += `/${item}`;
        if (!fs.existsSync(checkPath)) {
            fs.mkdirSync(checkPath);
        }
    }
}

/**
 * 是否为图片文件
 * @param {String} suffix
 * @return {Boolean}
 */
export const isImage = (suffix: string): boolean => {
    const imgTypes = ['png', 'jpg', 'jpeg', 'gif']
    return imgTypes.includes(suffix)
}
